package com.chenwy.example

import groovy.util.slurpersupport.NodeChild
import org.apache.commons.lang3.StringUtils
import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

class WanxiangResolver {

     static void main(String[] args) {
        XmlSlurper slurper = new XmlSlurper();
         System.out.println(WanxiangResolver.getClassLoader().getResourceAsStream("files/wanxiang1.rss"));
         System.out.println(WanxiangResolver.class.getResourceAsStream("files/wanxiang1.rss"));
        def pathResult = slurper.parse(WanxiangResolver.getClassLoader().getResourceAsStream("files/wanxiang1.rss"));
        if (pathResult && pathResult.channel && pathResult.channel.item) {
            int count = 0;
            List<NodeChild> items = pathResult.channel.item as List;
            Collections.sort(items , new Comparator<NodeChild>() {
                @Override
                int compare(NodeChild item1, NodeChild item2) {
                    String pubDate1 = item1.pubDate.text();
                    String pubDate2 = item2.pubDate.text();
                    return pubDate1 <=> pubDate2;
                }
            });
            items.each{
                item ->
                    String  extId = getExtId(item);
//                    System.out.println(extId);
                    if(StringUtils.isNotEmpty(extId) ){
                        def categoryId = '养生';
                        def tagId = '养生';
                        if (categoryId && tagId) {
                            ++count;
                            try {
                                Map article = makeArticle(categoryId, item);
//                                System.out.println(JsonOutput.toJson(article));
//                                System.out.println(article.create_at);
                                System.out.println(extId);
                                System.out.println(article.create_at);
                                Map articleTag = makeArticleTag(tagId, item);
                            } catch (Exception ex) {

                            }
                        }
                    }
            }
            System.out.println(String.format("共获取%d条资讯，其中新增%d条",pathResult.channel.item.size(),count));
//            System.out.println(requestSource());
        }
    }

   public static String getExtId(def item) {
        String link = item.link.text();
        String id = link.substring(link.lastIndexOf('/') + 1).replace('.html', '').trim();
        return id;
    }

    public static Map makeArticle(categoryId, def item) {
        [
                category_id  : categoryId,
                title        : item.title.text(),
                description  : item.description.text(),
                article_image: item.img.text(),
                model        : 'wanxiang',
                status       : 1,
                sort         : 255,
                create_at    : item.pubDate.text(),
                ext_id       : getExtId(item),
                '`from`'     : item.source.text(),
                type         : 'content',
                url          : item.link.text()
        ]
    }
    public static Map makeArticleTag(tagId, def item) {
        [
                tag_id      : tagId,
                status      : 1,
                sort        : 255,
                begin_time  : item.pubDate.text(),
                expire_time : '2026-01-01 00:00:00',
                image       : item.img.text(),
                image_num   : 1,
                style_type  : 1
        ]
    }

    private static  String requestSource() throws Exception {
        String url = "http://api.51yangsheng.com/api/xml/hltqzx.xml";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Accept-Encoding", "gzip");
        CloseableHttpResponse response = httpclient.execute(httpget);
        long start = System.currentTimeMillis();
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String data = EntityUtils.toString(entity);
//                logger.debug("Http Respond(status={}): {}", response.getStatusLine().getStatusCode(), data);
                int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    long now = System.currentTimeMillis();
                    long ttlb = now - start;
//                    logger.info("请求万象资讯API成功，用时{}毫秒",ttlb);
                    return data;
                } else {
                    throw new RuntimeException("{-+2}请求万象资讯API失败" , new Exception("error code=" + code + ", content: " + data));
                }
            } else {
                throw new RuntimeException("{-+2}请求万象资讯API失败, 返回内容为空,status="+response.getStatusLine().getStatusCode() );
            }
        } catch (Exception ex) {
            throw new RuntimeException("{-+2}请求万象资讯API失败" , ex);
        } finally {
            response.close();
        }
    }
}
